package com.example.demo.config.token;

import com.example.demo.entity.Token;
import com.example.demo.mapper.TokenMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenMapper tokenMapper;
    //提供查询
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {}
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {}
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        if ( arg0.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        //普通路径放行
        if ("/logic/user/login".equals(arg0.getRequestURI()) || "/logic/user/addUserInfo".equals(arg0.getRequestURI()) ) {
            return true;}
        //权限路径拦截
        arg1.setCharacterEncoding("UTF-8");
        OutputStream resultWriter=arg1.getOutputStream();
        log.info(arg0.getRequestURI()+"被拦截");
        final String headerToken=arg0.getHeader("Token");
        //判断请求信息
        if(null==headerToken||headerToken.trim().equals("")){
            resultWriter.write("{\"msg\":请先登录,\"state\":-1}".getBytes());
            resultWriter.flush();
            resultWriter.close();
            return false;
        }
        //解析Token信息
        Claims claims = Jwts.parser().setSigningKey("dahao").parseClaimsJws(headerToken).getBody();
        String tokenUserId=(String)claims.get("userid");
        //根据客户Token查找数据库Token
        Token token = new Token();
        token.setUserId(tokenUserId);
        Token myToken=tokenMapper.findByUserId(token);
        //数据库没有Token记录
        if(null==myToken) {
            resultWriter.write("{\"msg\":请先登录,\"state\":-1}".getBytes());
            resultWriter.flush();
            resultWriter.close();
            return false;
        }
            //数据库Token与客户Token比较
        if( !headerToken.equals(myToken.getToken()) ){
            resultWriter.write("{\"msg\":Token不合法,\"state\":50008}".getBytes());
            resultWriter.flush();
            resultWriter.close();
            return false;
        }
            //判断Token过期
        Date tokenDate=(Date)claims.getExpiration();
        int chaoshi=(int)(new Date().getTime()-tokenDate.getTime())/1000;
        if(chaoshi>60*60*24*3){
            resultWriter.write("{\"msg\":Token已过期,\"state\":50014}".getBytes());
            resultWriter.flush();
            resultWriter.close();
            return false;
        }
        //最后才放行
        //arg1.reset();
        return true;
    }
}
